package com.example.myshools.Mine.organization;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.myshools.Mine.organization.edit.PersonalData;
import com.example.myshools.Mine.organization.historyActivityManage.HistoryActivity;
import com.example.myshools.Mine.organization.publish.IdentificationResult;
import com.example.myshools.Mine.organization.publish.PublishNewsActivity;
import com.example.myshools.R;
import com.example.myshools.entity.Constant;
import com.example.myshools.entity.Orgnaization;
import com.example.myshools.entity.Student;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MineFragment extends Fragment {
    private ImageView headImg;
    private ImageView isRenZ;//认证出现
    private ImageView inToJS;
    private TextView oName;
    private TextView oLevel;
    private TextView isRenZh;
    private LinearLayout upActivity;
    private LinearLayout historyActivity;
    private LinearLayout myNews;
    private LinearLayout mySchoolFriend;
    private LinearLayout settings;
    private LinearLayout ren_z_status;
    private int role;
    private int id;
    private Orgnaization orgnaization = new Orgnaization();
    private Student student = new Student();
    private Gson gson = new Gson();
    private SharedPreferences sharedPreferences;
    private static String user_head_path = null;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View newView = inflater.inflate(R.layout.mine_fragment, container, false);


        //根据id,查询个人信息
        //首先判断是组织还是个人
       //0是组织，1是个人，在登录的时候设置全局变量,获取用户id值
        role=getActivity().getSharedPreferences("role",Context.MODE_PRIVATE).getInt("role",-1);
        id =getActivity().getSharedPreferences("user",Context.MODE_PRIVATE).getInt("userId",-1);
        return newView;
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


        headImg = getActivity().findViewById(R.id.o_head_img);
        oName = getActivity().findViewById(R.id.o_name);
        oLevel = getActivity().findViewById(R.id.o_level);
        isRenZ = getActivity().findViewById(R.id.is_ren_zheng);
        isRenZh = getActivity().findViewById(R.id.ren_zheng);
        inToJS = getActivity().findViewById(R.id.btn_into_xiangqing);
        upActivity = getActivity().findViewById(R.id.up_activity);
        historyActivity = getActivity().findViewById(R.id.history_activity);
        myNews = getActivity().findViewById(R.id.my_news);
        mySchoolFriend = getActivity().findViewById(R.id.my_school_friend);
        settings = getActivity().findViewById(R.id.settings);
        ren_z_status=getActivity().findViewById(R.id.renz_status);
        getUserData(new Message());
        setAdapter();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //EventBus.getDefault().unregister(this);
    }

    private void setAdapter() {
        MyClickListener my = new MyClickListener();
        inToJS.setOnClickListener(my);
        upActivity.setOnClickListener(my);
        historyActivity.setOnClickListener(my);
        myNews.setOnClickListener(my);
        mySchoolFriend.setOnClickListener(my);
        settings.setOnClickListener(my);
        ren_z_status.setOnClickListener(my);
    }

    private void setView(int r) {


        Message message = new Message();
        message.what = 3;
        message.obj = r;
        handler.sendMessage(message);

            Log.e("ss========------", orgnaization.getHeadPath().toString());
           /* String path = orgnaization.getHeadPath().toString();
            Glide.with(this).load(path).apply(requestOptions).into(headImg);*/
            oName.setText(orgnaization.getName() + "");
            oLevel.setText(orgnaization.getLevel() + "");
            if (orgnaization.getIdentity() == 0) {
                isRenZ.setVisibility(View.GONE);
                isRenZh.setText("未认证");
            } else if (orgnaization.getIdentity() == 2) {
                isRenZ.setVisibility(View.GONE);
                isRenZh.setText("正在认证中");
            } else {
                isRenZ.setVisibility(View.VISIBLE);
                isRenZh.setText("已认证");
            }


    }


    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void getUserData(Message message) {
        OkHttpClient okHttpClient = new OkHttpClient();
        FormBody body = new FormBody.Builder().add("id", String.valueOf(id)).build();
        String url = Constant.url + "user/findOrganizationById";
        final Request request = new
                Request.Builder().url(url).post(body).build();
        final Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("de===", "连接失败！！！！！！！");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Log.e("ss", string.toString());
                Message message = new Message();
                message.what = 1;
                message.obj = string;
                handler.sendMessage(message);
            }
        });

    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            RequestOptions requestOptions = new RequestOptions().placeholder(R.drawable.loading).fallback(R.drawable.loading).error(R.drawable.headfail).diskCacheStrategy(DiskCacheStrategy.ALL).circleCrop();
            if (msg.what == 1) {
                Gson gson = new GsonBuilder().serializeNulls().create();

                    orgnaization = gson.fromJson(msg.obj.toString(), Orgnaization.class);
                    if (user_head_path == null&&orgnaization.getHeadPath()!=null) {
                        user_head_path = orgnaization.getHeadPath();
                        Glide.with(getContext()).load(orgnaization.getHeadPath()).apply(requestOptions).into(headImg);
                    }

                setView(role);
            }
            if (msg.what == 3) {
                    if(user_head_path!=null&&user_head_path!=orgnaization.getHeadPath()) {
                        Glide.with(getContext()).load(orgnaization.getHeadPath()).apply(requestOptions).into(headImg);
                    }
            }
            if (msg.what == 10) {

                getUserData(new Message());
                setAdapter();
            }


        }
    };

    private class MyClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {

            switch (view.getId()) {

                case R.id.btn_into_xiangqing:
                        Intent intent = new Intent(getActivity(), PersonalData.class).putExtra("o", gson.toJson(orgnaization));
                        startActivity(intent);
                        break;

                case R.id.up_activity:
                    Intent intent1 = new Intent(getActivity(), PublishNewsActivity.class);
                    startActivity(intent1);
                    break;
                case R.id.history_activity:
                    Intent intent2=new Intent(getActivity(), HistoryActivity.class);
                    startActivity(intent2);
                    break;

                case R.id.renz_status:
                    Intent intent3=new Intent(getActivity(), IdentificationResult.class).putExtra("who",666);
                    startActivity(intent3);
                    break;


            }

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.e("onResume", "onResum");
        Message message = new Message();
        message.what = 10;
        handler.sendMessage(message);
    }

}

